package com.qdlc.p2p.biz.adapted.impl;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.qd.p2p.adapter.AdaptePlatform;
import com.qd.p2p.adapter.enums.ResponseStatus;
import com.qd.p2p.adapter.param.WithdrawParameter;
import com.qd.p2p.adapter.response.GenericResponse;
import com.qdlc.p2p.biz.processor.TaskProcessorHelper;
import com.qdlc.p2p.biz.processor.event.AccountCashModelValueEvent;
import com.qdlc.p2p.biz.util.SinaNotifyRequestHandler;
import com.qdlc.p2p.common.constant.AccountCashFeeBear;
import com.qdlc.p2p.common.constant.AccountCashStatus;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.core.queue.ITaskProcessor;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.NumberUtil;
import com.qdlc.p2p.common.util.OrderNoUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dto.AccountCash;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.util.UserTypeUtils;

/**
 * 功能描述: [新浪][提现]接口实现类
 * @author linya
 * @date 2016-4-22
 */
@Service
public class AdaptedSinaWithdrawService extends AbstractAdaptedWithdrawService{

    @Override
    public ReturnResult doWithdraw(User user, String bankNo, double money, String ip) {

        //手续费(只有普通用户收取)
        double servFee = 0D;
        boolean basicUserType = UserTypeUtils.isNatural(user.getUserId());
        if (basicUserType) {
            servFee = SystemConfigHelper.getDoubleValue(Nid.CASH_SERV_FEE);
        }
        
        //平台手续费，应该根据提现金额来获取
        double webCashFee = NumberUtil.format2(SystemConfigHelper.getDoubleValue(Nid.WEB_CACH_FEE) * money);

        //提现(2位小数位)
		double amount = BigDecimalUtil.sub(BigDecimalUtil.sub(money, servFee),webCashFee);
		amount = NumberUtil.format2(amount);
		String platformUserId = user.getTppUserCustId();
		
		//请求提现支付接口
		WithdrawParameter withdrawParameter = new WithdrawParameter();
		withdrawParameter.setPlatformUserId(platformUserId);
		withdrawParameter.setAmount(amount);
		withdrawParameter.setFee(servFee);
		withdrawParameter.setFeeTakenOn(1);
		withdrawParameter.setBankNo(bankNo);
		withdrawParameter.setOrderId(OrderNoUtil.getInstance().getSerialNumber());
		GenericResponse response = adaptedPayService.withdraw(withdrawParameter);
		if(response == null){
			return new ReturnResult("系统繁忙,请稍后再试!");
		}
		log.info(MessageFormat.format("++++[用户{0}提现{1},订单号{2}提现{3}元]", user.getUserName(), response.isSuccess() ? "成功" : "失败", withdrawParameter.getOrderId(), money));
		
		//构建提取记录，并保存到数据库中
		AccountCash accountCash = new AccountCash();
		accountCash.setUserId(user.getUserId());
		accountCash.setOrderNo(withdrawParameter.getOrderId());
		accountCash.setAddTime(DateUtil.getNow());
		accountCash.setAddIp(ip);
		accountCash.setMoney(money);
		accountCash.setAmount(BigDecimalUtil.sub(BigDecimalUtil.sub(money, servFee),webCashFee));
		accountCash.setFee(BigDecimalUtil.add(servFee + webCashFee));
		String bankName = accountBankService.getBankNameByCardNo(user.getUserId(), bankNo);
		accountCash.setBank(bankName);
		accountCash.setBankNo(bankNo);
		accountCash.setFeeBear(AccountCashFeeBear.PERSONAL.getCode());

		//判断提现是否成功
		ResponseStatus status = response.getStatus();
		if(ResponseStatus.FAILURE.equals(status)){
			accountCash.setStatus(AccountCashStatus.FAIL);
			return new ReturnResult("提现失败,原因:" + response.getResponseMsg());
		}else{
			accountCash.setStatus(AccountCashStatus.APPLY);
			saveAccountCash(user, accountCash);
			return ReturnResult.SUCCESS;
		}
	}
	
	@Override
	public AdaptePlatform supportPlatform() {
		return AdaptePlatform.SINA;
	}

	/**
	 * 回调通知
	 * @param request
	 * @return
	 */
	@Override
	public ReturnResult notifying(HttpServletRequest request) {
		
        SinaNotifyRequestHandler notifyRequest = SinaNotifyRequestHandler.build(request);
        boolean result = notifyRequest.checkSign();
        
        if(!result){
        	log.info("++++ [新浪][取现回调] 取现异步回调失败.");
        	return new ReturnResult("sign error");
        	
        }
        
        String withdrawStatus = notifyRequest.getParam("withdraw_status");
        String outTradeNo = notifyRequest.getParam("outer_trade_no");

        try {
			AccountCashModelValueEvent event = new AccountCashModelValueEvent();
			event.setOrderNo(outTradeNo);
			event.setStatus(withdrawStatus);
			ITaskProcessor taskProcessor = TaskProcessorHelper.getProcessor(event.getTaskProcessorClass());
			taskProcessor.process(event);
		} catch (TaskProcessorException e) {
			e.printStackTrace();
			log.info("++++ [新浪][取现回调] 取现异步回调失败.");
		}

        log.info("++++ [新浪][取现回调] 取现异步回调成功");
		return ReturnResult.SUCCESS;
	}
	
}
